<?php
class FriendAction extends Action{
	private $friendship;

	public function __construct()
	{
		parent::__construct();

		$this->friendship = new FriendShipModel();

		if($this->session->getAttr("uid") == null){
			$this->forward("Index");
		}
	}
	
	protected function init()
	{

	}
	public function display()
	{
		
	}
	public function addFriend()
	{
		$friend_a = $this->session->getAttr('uid');
		$friend_b = $this->get['uid'];

		$friend_b = (int) $friend_b;

		if($friend_b <= 0)
		{
			$this->showMessage("执行了非法操作！");
		}
		/****************************/
		/*      2008-9-8 张伟       */
		/*  判断是否为添加自己为好友*/
		/****************************/
		if($friend_a==$friend_b)
		{
			$this->showMessage("不能添加自己为好友！");
		}
		/*end*/

		$this->friendship->addCondition('friend_a', '=', $friend_a, "AND");
		$this->friendship->addCondition('friend_b', '=', $friend_b, 'OR');
		$this->friendship->addCondition('friend_a', '=', $friend_b, "AND");
		$this->friendship->addCondition('friend_b', '=', $friend_a, "");


		//echo $this->friendship->toSql("select");
		$fs = $this->friendship->findOne();

		if(!$fs)
		{
			$this->friendship->friend_a = $friend_a;
			$this->friendship->friend_b = $friend_b;
			$this->friendship->friend_type = 0;
			if($this->friendship->add())
			{
				$msg = "好友申请成功提交！等待确认。";
			}else
			{
				$msg = "申请失败！请联系管理员!";
			}
			$this->showMessage($msg);
		}else{
			if($fs['friend_type'] == 0)
			{
				if($fs['friend_b'] == $friend_a){
					$this->friendship->friend_a = $fs['friend_a'];
					$this->friendship->friend_b = $fs['friend_b'];
					$this->friendship->friend_type = 1;
					$this->friendship->addCondition('friend_a', '=', $fs['friend_a'], 'and');
					$this->friendship->addCondition('friend_b', '=', $fs['friend_b'], '');
					if($this->friendship->update())
					{
						$msg = "添加好友成功！";
					}else{
						$msg = "添加好友失败！请联系管理员！";
					}
					$this->showMessage($msg);

				}else{
					$this->showMessage("申请已经提交！");
				}
			}else{
				$this->showMessage("添加好友成功！");
			}
		}
	}

	public function doView()
	{
		$this->friendship->addCondition('friend_b', '=', $this->session->getAttr('uid'), "and");
		$this->friendship->addCondition('friend_type', '=', "0", "");
		$apps = $this->friendship->find();

		$this->smarty->assign('apps', $apps);
		$this->smarty->display("Friend.tpl");
	}
};
?>

